﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO;

namespace WOWMultiPlay
{
    public static class Helper_FileEncoding
    {
        public static void CheckFileEncodingAndChange(string FilePath, Encoding ExpectedEncoding)
        {
            if (GetFileEncoding(FilePath) != ExpectedEncoding)
            {
                StreamReader SR = new StreamReader(FilePath);
                string FileContent = SR.ReadToEnd();
                SR.Close();

                StreamWriter SW = new StreamWriter(FilePath, false, ExpectedEncoding);
                SW.Write(FileContent);
                SW.Close();
            }
        }

        private static Encoding GetFileEncoding(string FilePath)
        {
            FileStream FS = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            System.Text.Encoding FileEncoding = GetEncoding(FS);
            FS.Close();
            return FileEncoding;
        }
        private static Encoding GetEncoding(FileStream FS)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF };

            BinaryReader BinReader = new BinaryReader(FS, Encoding.Default);
            byte[] ss = BinReader.ReadBytes(3);
            BinReader.Close();

            if (ss.Length > 0)
            {
                if (ss[0] >= 0xEF)
                {
                    if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
                    {
                        return Encoding.UTF8;
                    }
                    else if (ss[0] == 0xFE && ss[1] == 0xFF)
                    {
                        return Encoding.BigEndianUnicode;
                    }
                    else if (ss[0] == 0xFF && ss[1] == 0xFE)
                    {
                        return Encoding.Unicode;
                    }
                }
            }

            return Encoding.Default;
        }
    }
}